import { useEffect, useState, Suspense } from 'react'
import { Outlet, useNavigate } from 'react-router'
import packageJson from '../../../package.json';

import PageLoading from '../../component/pageLoading'

import { jumpTo } from '../../utils/jump'

import { List, Image, Tooltip, Tag, message } from "antd";
import { UserOutlined } from '@ant-design/icons';
import { Toast } from 'antd-mobile'

import { menuData } from '../../constant/leftMenuData'

import logo from '../../res/push_log.png'

import styles from './index.module.css'

//缓存
import { putCache, getCache, removeAllCache } from '../../utils/cache'
import { current_menu_item_key } from '../../utils/cache/cacheKey'

//api
import { getUserInfo } from '../../utils/axiosRequest/api'


function Mian() {
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    //导航
    const navigate = useNavigate()
    const [version, setVersion] = useState('');
    //默认选中第一个
    const [selectedIndex, setSelectedIndex] = useState(() => {
        return getCache(current_menu_item_key, '0');
    });
    const [currentTime, setCurrentTime] = useState('');
    const [weekDay, setWeekDay] = useState('');
    const [fullDate, setFullDate] = useState('');

    //[]空数组相当于componentDidMount
    useEffect(() => {
        //设置版本号
        setVersion(packageJson.version);
        // 设置时间，立即更新一次
        updateTime();
        // 获取用户信息
        const params = new Map()
        getUserInfo(params)
            .then(response => {
                const data = response.data
            })
            .catch(error => {
            });
        // 每秒更新
        const timer = setInterval(updateTime, 1000);
        return () => {
            clearInterval(timer)
        }
    }, []);

    //监听selectedIndex的状态
    useEffect(() => {
        putCache(current_menu_item_key, selectedIndex, '0');
    }, [selectedIndex]);

    const updateTime = () => {
        // 格式化时间：HH:MM:SS
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        setCurrentTime(`${hours}:${minutes}:${seconds}`);

        // 格式化星期几
        const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const dayOfWeek = weekDays[now.getDay()];
        setWeekDay(dayOfWeek);

        // 格式化年月日
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const date = String(now.getDate()).padStart(2, '0');
        setFullDate(`${year}-${month}-${date}`);
    };

    const handleItemClick = (item, index) => {
        switch (index) {
            case 0:
                setSelectedIndex(index)
                jumpTo(navigate, '/main/pushCase', true, null)
                break;

            // case 1:
            //     jumpTo(navigate, '/main/test2', true, null)
            //     break;

            default:
                messageApi.open({ type: 'error', content: '该模块建设中' });
                break;
        }
    };

    const getItemClassName = (index) => {
        const baseClass = styles.left_menu_item;
        const selectedClass = styles.left_menu_item_selected;
        const isSelected = selectedIndex == index;
        if (isSelected) {
            return selectedClass;
        }
        return baseClass;
    };

    function logout() {
        const toast = Toast.show({
            maskClickable: false,
            icon: 'loading',
            duration: 0,
            content: '正在退出...',
        })
        setTimeout(() => {
            removeAllCache();
            toast.close();
            jumpTo(navigate, '/', true, null)
        }, 2000);
    }

    return (
        <div className={styles.container}>
            {contextHolder}
            <div className={styles.left_menu_box}>
                <List
                    header={
                        <div className={styles.left_menu_head}>
                            <Image preview={false} width={25} src={logo} />
                            <span className={styles.left_menu_head_title} >推送管理系统</span>
                        </div>
                    }
                    bordered={false}
                    split={false}
                    dataSource={menuData}
                    renderItem={(item, index) => (
                        <div onClick={() => handleItemClick(item, index)} className={getItemClassName(index)} >
                            <div className={styles.left_menu_item_icon}>
                                {item.icon}
                            </div>
                            <span> {item.label}</span>
                        </div>
                    )}
                />
                <div className={styles.left_menu_bottom}><span>version：{version}</span></div>
            </div>
            <div className={styles.right_container}>
                <div className={styles.right_head_box}>
                    <div className={styles.show_time_box}>
                        <div className={styles.time_box}>
                            <span className={styles.time_display}>{currentTime}</span>
                        </div>
                        <div className={styles.date_box}>
                            <span className={styles.date_display}>{weekDay}</span>
                            <span className={styles.date_display}>{fullDate}</span>
                        </div>
                    </div>
                    <div className={styles.user_info_box}>
                        <Tooltip title="点击退出登录">
                            <Tag onClick={logout} icon={<UserOutlined />} color="#1677ff">用户：admin</Tag>
                        </Tooltip>
                    </div>
                </div>
                <div className={styles.right_content_box}>
                    <Suspense fallback={<PageLoading />}>
                        <Outlet ></Outlet>
                    </Suspense>
                </div>
            </div>
        </div >
    )
}


export default Mian

